package com.coupon.template.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName HealthCheckController.java
 * @create 2023年06月25日 下午5:21
 * @Description 健康监测接口
 * @Version V1.0
 */
@Slf4j
@RestController
public class HealthCheckController {

    // 服务发现客户端
    @Resource
    private DiscoveryClient client;
    // 服务注册接口，提供了获取服务id的方法
    @Resource
    private Registration registration;

    // 健康检查接口
    // url: localhost:7001/coupon-template/health
    @GetMapping("/health")
    public String health(){
        log.info("Health Check");
        return "CouponTemplate Is OK!";
    }

    // 异常测试接口
    // url: localhost:7001/coupon-template/exception
    @GetMapping("/exception")
    public String exception(){
        log.info("Exception Test");
        throw new RuntimeException("CouponTemplate Has Some Problem");
    }

    // 获取Eureka Server上的微服务元信息
    // url: localhost:7001/coupon-template/info
    @GetMapping("/info")
    public List<Map<String,Object>> info(){
        // 大约需要等待两分钟才能获取到注册信息

        // 获取服务id
        String instanceId = registration.getInstanceId();
        // 获取服务元信息
        List<ServiceInstance> instances = client.getInstances(instanceId);

        List<Map<String,Object>> result = new ArrayList<>(instances.size());

        instances.forEach(i -> {
            Map<String,Object> info = new HashMap<>();
            info.put("serviceId",i.getServiceId());
            info.put("instanceId",i.getInstanceId());
            info.put("port",i.getPort());
            info.put("uri",i.getUri());
            result.add(info);
        });

        return result;
    }

}
